//
//  TTDianpuManagerViewController.m
//  TaoTuo
//
//  Created by admin on 2019/11/4.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDianpuManagerViewController.h"
#import "LLSegmentView.h"
#import "TTDianpuManagerViewCell.h"
#import "TTDianpuManagerHeaderView.h"
#import "TTDianpuManagerModel.h"
#import "TTRenewalResultViewController.h"

#import "TTDianpuSetViewController.h"
#import "TTShopManagerSetViewController.h"
#import "TTBeiLvSetViewController.h"

#import "TTRenewalViewController.h"

#import "TTOpenShopViewController.h"

@interface TTDianpuModel ()

@end

@implementation TTDianpuModel

+ (instancetype)setModelWithImageName:(NSString *)imageName title:(NSString *)title
{
    TTDianpuModel *model = [[self alloc] init];
    model.imageName = imageName;
    model.title = title;
    return model;
}

@end


static NSString *cellID = @"cell";

@interface TTDianpuManagerViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) TTDianpuManagerHeaderView *headerView;
@property (nonatomic, strong) TTDianpuManagerModel *managerModel;

@end

@implementation TTDianpuManagerViewController

- (UIStatusBarStyle)preferredStatusBarStyle
{
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleDarkContent;
    } else {
        return UIStatusBarStyleDefault;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"店铺管理";
    [self setupRightBarButtonItem];
    
    [self getNetworkData];
    
    // 设置 商品管理、倍率设置、商城设置、续费 以及 订单管理状态变化之后通知请求
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworkData) name:@"refreashDatas" object:nil];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuManagerViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        TTShopManagerSetViewController *shopSetVC = [[TTShopManagerSetViewController alloc] initWithManagerModel:self.managerModel];
        [self.navigationController pushViewController:shopSetVC animated:YES];
    } else if (indexPath.row == 1) {
        TTBeiLvSetViewController *beiLvVC = [[TTBeiLvSetViewController alloc] initWithManagerModel:self.managerModel];
        [self.navigationController pushViewController:beiLvVC animated:YES];
    } else if (indexPath.row == self.dataArray.count - 1) {
        TTDianpuSetViewController *setVC = [[TTDianpuSetViewController alloc] initWithManagerModel:self.managerModel];
        [self.navigationController pushViewController:setVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 45)];
    UILabel *label = [UILabel labelWithTitle:@"商城管理" color:UIColorHex(333333) fontSize:18];
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view).mas_offset(10);
        make.left.mas_equalTo(10);
    }];
    UIButton *btn = [UIButton createButtonWithTitle:@"浏览商城" titleColor:UIColorHex(FFBB20) titleFont:[UIFont systemFontOfSize:16] backgroundColor:nil target:self action:@selector(lookShop)];
    [view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label);
        make.right.equalTo(view).mas_offset(-10);
    }];
    return view;
}

///浏览商城
- (void)lookShop
{
    NSString *domainStr = [TTLoginSingle sharedSingle].userModel.ShopDomainName;
    if (domainStr.length > 0) {
        domainStr = [domainStr urlEncode];
    }
    NSURL *url = [NSURL URLWithString:domainStr];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)getNetworkData
{
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:shopInfo_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.managerModel = [TTDianpuManagerModel modelWithJSON:responseObject];
        
        self.headerView.model = self.managerModel;
        self.tableView.tableHeaderView = self.headerView;
        [self setupFooterView];
        [self setupDatas];
        
        ///下载微信分享图片
        if (self.managerModel.ShareImg.length > 0) {
            NSString *imageUrlString = [self.managerModel.ShareImg urlEncode];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
                self.headerView.imageData = imageData;
            });
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}


// 去续费
- (void)renewalBtnClick
{
    TTRenewalViewController *renewalVC = [[TTRenewalViewController alloc] init];
    [self.navigationController pushViewController:renewalVC animated:YES];
}

// 设置导航栏右边bar
- (void)setupRightBarButtonItem
{
    @weakify(self)
    LLSegmentView *segment = [[LLSegmentView alloc] initWithFrame:CGRectMake(0, 0, 90, 30) items:@[[UIImage imageNamed:@"dianputhreedot"], [UIImage imageNamed:@"dianpuquan"]] selectItemBlock:^(NSInteger index, UIButton *selectItemButton) {
        @strongify(self)
        if (index == 0) {
            [self.headerView shareDianpuBtnClick];
        } else if (index == 1) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }];
    segment.layer.cornerRadius = 15;
    segment.layer.borderColor = UIColorHex(EEEEEE).CGColor;
    segment.layer.borderWidth = 0.5;
    [segment setFont:[UIFont systemFontOfSize:14]];
    [segment setSelectFont:[UIFont systemFontOfSize:16]];
    [segment setTitleColor:[UIColor blackColor]];
    [segment setSelectTitleColor:[UIColor cyanColor]];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segment];
}

- (void)setupFooterView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 100)];
    NSString *title = [NSString stringWithFormat:@"— %@ 商城到期 —", self.managerModel.ShopExpireDate];
    UILabel *label = [UILabel labelWithTitle:title color:UIColorHex(CCCCCC) fontSize:11];
    [footerView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.centerX.equalTo(footerView);
    }];
    
    // 如果显示店铺信息的话才显示
    if ([TTLoginSingle sharedSingle].mineDianpuShow) {
        
        UIButton *btn = [UIButton createButtonWithTitle:@"去续费" titleColor:UIColorHex(F4CA3A) titleFont:[UIFont systemFontOfSize:11] backgroundColor:nil target:self action:@selector(renewalBtnClick)];
        btn.contentEdgeInsets = UIEdgeInsetsMake(9, 6, 9, 6);
        [footerView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(label.mas_bottom);
            make.centerX.equalTo(footerView);
        }];
        
    }
    
    
    self.tableView.tableFooterView = footerView;
    
    NSDate *expireDate = [NSDate dateWithString:self.managerModel.ShopExpireDate format:@"yyyy-MM-dd"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *nowStr = [formatter stringFromDate:[NSDate date]];
    NSDate *nowDate = [NSDate dateWithString:nowStr format:@"yyyy-MM-dd"];
    
    NSLog(@">> %@, %@", expireDate, nowDate);
    NSComparisonResult result = [nowDate compare:expireDate];
    if (result == NSOrderedDescending) {
        TTOpenShopViewController *openVC = [[TTOpenShopViewController alloc] initWithRenewal:YES];
        [self.navigationController pushViewController:openVC animated:YES];
    }
    
    
}

- (void)setupDatas
{
    [self.dataArray removeAllObjects];
    [self.dataArray addObject:[TTDianpuModel setModelWithImageName:@"shangpin" title:@"商品管理"]];
    [self.dataArray addObject:[TTDianpuModel setModelWithImageName:@"beilvshezhi" title:@"倍率设置"]];
    [self.dataArray addObject:[TTDianpuModel setModelWithImageName:@"shangcheng" title:@"商城设置"]];
    [self.tableView reloadData];
}



- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 100;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        [_tableView registerClass:[TTDianpuManagerViewCell class] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (TTDianpuManagerHeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [[TTDianpuManagerHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 240)];
        @weakify(self)
        [_headerView.subject subscribeNext:^(id  _Nullable x) {
            @strongify(self)
            TTDianpuSetViewController *setVC = [[TTDianpuSetViewController alloc] initWithManagerModel:self.managerModel];
            [self.navigationController pushViewController:setVC animated:YES];
        }];
    }
    return _headerView;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"店铺管理页面释放了");
}

@end


 
